<template>
  <div class="home">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="标题">
        <el-input
          v-model="formInline.detail"
          clearable
          placeholder="请输入要搜索的内容"
          @keyup.enter.native="getList"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getList">查询</el-button>
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button type="warning" @click="handleDelete">删除</el-button>
      </el-form-item>
    </el-form>
    <el-table
      v-loading="loading"
      ref="multipleTable"
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column prop="title" label="标题" width="180"></el-table-column>
      <el-table-column
        prop="content"
        label="内容"
        width="180"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="create_time"
        label="创建时间"
        :formatter="formatterDate"
      ></el-table-column>
      <el-table-column prop="delete_time" label="删除时间"></el-table-column>
      <el-table-column fixed="right" label="操作" width="100">
        <template slot-scope="scope">
          <el-button @click="handleEdit(scope.row)" type="text">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @current-change="handleCurrentChange"
      :current-page.sync="currentPage1"
      :page-size="pageSize"
      layout="total, prev, pager, next"
      :total="total"
    >
    </el-pagination>

    <!-- 新增 -->
    <el-dialog
      :title="dialogType == 'add' ? '新增' : '编辑'"
      :visible.sync="addDialogVisible"
      width="60%"
      center
      @close="dialogClose"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="ruleForm.title"
            placeholder="请输入标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="新闻类别" prop="type">
          <el-select v-model="ruleForm.type" placeholder="请选择新闻类别">
            <el-option label="行业资讯" value="0"></el-option>
            <el-option label="公司新闻" value="15"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="create_time" label="创建时间">
          <!-- {{ ruleForm.create_time }} -->
          <el-date-picker
            type="date"
            placeholder="选择日期"
            value-format="timestamp"
            v-model="ruleForm.create_time"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        <el-form-item prop="delete_time" label="删除时间">
          <el-date-picker
            type="date"
            placeholder="选择日期"
            value-format="timestamp"
            v-model="ruleForm.delete_time"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            type="textarea"
            v-model="ruleForm.content"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('ruleForm')"
          >确 定</el-button
        >
        <el-button @click="addDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getList, getSave, getUpdate } from "@/api/index.js";
// @ is an alias to /src

export default {
  name: "Home",
  data() {
    return {
      tableData: [],
      currentPage1: 1,
      total: 0,
      curPage: 1,
      pageSize: 15,
      formInline: {
        detail: "",
      },
      addDialogVisible: false,
      ruleForm: {
        title: "",
        type: "",
        create_time: "",
        delete_time: "",
        content: "",
      },
      // 校验规则,和prop要相对应
      rules: {
        title: [
          { required: true, message: "请输入标题", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        type: [
          { required: true, message: "请选择活动区域", trigger: "change" },
        ],
        create_time: [
          { required: true, message: "请选择日期", trigger: "change" },
        ],
        delete_time: [
          { required: true, message: "请选择时间", trigger: "change" },
        ],
        content: [{ required: true, message: "请填写内容", trigger: "blur" }],
      },
      loading: false,
      dialogType: "add",
      sels: [],
    };
  },
  watch: {
    formInline: {
      handler(newVal) {
        console.log(newVal);
        if (!newVal.detail) {
          this.getList();
        }
      },
      deep: true,
    },
  },
  methods: {
    dialogClose() {
      this.ruleForm = {
        title: "",
        type: "",
        create_time: "",
        delete_time: "",
        content: "",
      };
    },
    submitForm(formName) {
      console.log(this);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogType == "add") {
            let ruleForm = {};
            ruleForm = JSON.parse(JSON.stringify(this.ruleForm));
            for (const key in ruleForm) {
              if (Object.hasOwnProperty.call(ruleForm, key)) {
                //hasOwnProperty过滤不属于自己的属性
                if (key === "create_time" || key === "delete_time") {
                  // ruleForm[key] = ruleForm[key].toString().substr(0, 10);
                  ruleForm[key] = ruleForm[key] / 1000;
                }
              }
            }
            getSave(ruleForm).then((res) => {
              console.log(res);
              if (res.data.code === 0) {
                this.getList();
                this.addDialogVisible = false;
              }
            });
          } else if (this.dialogType == "edit") {
            // getUpdate(this.ruleForm).then((res) => {
            //   if (res.data.code == 0) {
            //     this.$message.success("修改成功");
            //     this.getList();
            //     this.addDialogVisible = false;
            //   }
            // });
            this.$http
              .post("/api/api/news/update", { ...this.ruleForm })
              .then((res) => {
                if (res.data.code === 0) {
                  console.log(this);
                  this.$message.success("修改成功");
                  this.getList();
                  this.addDialogVisible = false;
                }
              });
          }
        }
      });
    },
    handleAdd() {
      console.log(this);
      this.addDialogVisible = true;
      this.dialogType = "add";
      this.$nextTick(() => {
        this.$refs["ruleForm"].clearValidate();
      });
    },
    // onSubmit() {
    //   let params = {
    //     title: this.formInline.detail,
    //   };
    //   // getList({ params }).then((res) => {});
    // },
    handleCurrentChange(page) {
      console.log(page);
      this.curPage = page;
      this.getList();
    },
    formatterDate(row, column) {
      return this.formatDate(new Date(row.create_time * 1000), "yyyy-MM-dd");
    },
    getList() {
      this.loading = true;
      getList({
        page: this.curPage,
        limit: this.pageSize,
        title: this.formInline.detail,
      })
        .then((res) => {
          this.loading = false;
          let {
            data: { newsList },
          } = res;
          this.tableData = newsList;
          this.total = res.data.count;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    handleEdit(row) {
      console.log(row);
      this.addDialogVisible = true;
      this.dialogType = "edit";
      for (const key in row) {
        if (Object.hasOwnProperty.call(row, key)) {
          if (key === "create_time" || key === "delete_time") {
            row[key] = row[key] * 1000;
          } else if (key === "type") {
            // row[key] = row[key] + '';
            // row[key] = row[key].toString();
            row[key] = String(row[key]);
          }
        }
      }
      this.ruleForm = row;
    },
    handleSelectionChange(sel) {
      this.sels = sel;
    },
    handleDelete() {
      let arr = [];
      if (!this.sels.length) {
        this.$message.warning("请至少选择一条数据!");
        return false;
      }
      this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        console.log("wangjin");
        for (const key in this.sels) {
          let { id } = this.sels[key];
          arr.push(id);
        }
        // this.$http.post('/api/news/delete', { id: arr });
      });
    },
  },
  created() {
    // this.$http.get('http://macio.ncyateng.com/api/news/index',{params:{}})
    // .then((res)=>{  //只能用箭头函数，不能使用普通函数，因为如果普通函数这里this就不一样了
    //   console.log(res);
    //   let {data:{newsList}}=res;
    //   this.tableData=newsList;
    // })
    this.getList();
  },
};
</script>

<style lang="scss" scoped>
.el-select {
  display: block;
}
</style>